package com.gupaoedu.vip.netty.io.nio.tomcat.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

/**
 * @program:gupaoedu-vip-netty-io
 * @description:Netty版本Response
 * @author:Gongchao
 * @date:2020-04-28
 **/
public class GPResponse {

    //SocketChannel的封装
    private ChannelHandlerContext channelHandlerContext;

    private HttpRequest httpRequest;

    public GPResponse(ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest) {
        this.channelHandlerContext = channelHandlerContext;
        this.httpRequest = httpRequest;
    }

    public void write(String out) throws Exception{
        if(out == null || out.length() == 0) {
            return ;
        }
        try{
            //设置http协议及请求头信息
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(
                    //设置http版本
                    HttpVersion.HTTP_1_1,
                    //设置响应码
                    HttpResponseStatus.OK,
                    //设置编码
                    Unpooled.wrappedBuffer(out.getBytes("UTF-8"))
            );

            fullHttpResponse.headers().set("Content-Type","text/html");
            // 当前是否支持长连接
//            if (HttpUtil.isKeepAlive(r)) {
//                // 设置连接内容为长连接
//                fullHttpResponse.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
//            }
            channelHandlerContext.write(fullHttpResponse);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            channelHandlerContext.flush();
            channelHandlerContext.close();
        }
    }
}
